import requests
import sys

from plugins.plugin import Plugin

sys.path.append("..")
from src.video import Video
from src.playlist import Playlist
from src.history import History
from src.config import Config

class Anilibria(Plugin):

    def __init__(self, history: History=History(), config: Config=Config()) -> None:
        super().__init__(history, config)
        self.history = history
        self.config = config

        self.name = "[+] AnilibriaTV: Search"
        self.category = "AnilibriaTV"

        self.query_description = """"""

        self.params = {
            'query'         : True,
            'api_instance'  : False 
        }

        self.flag = "-als"
        self.full_flag = "--anilibriasearch"
        self.flag_help = "search anilibria titles"
        self.flag_action = ""

        self.save_config()

        self.api_instance = self.config.get_option(self.category, 'api-instance')
        self.instance = self.config.get_option(self.category, 'instance')

    def get_search(self, params):
        api_instance = self.api_instance
        if 'api_instance' in params:
            api_instance = params['api_instance']

        resp = requests.get(f"{api_instance}/searchTitles", 
            {
                "search" : params['query']
            }
        )

        if resp.status_code != 200: return list()
        resp = resp.json()

        items = []
        for it in resp:
            title = f"{it['names']['ru']} ({it['names']['en']})"
            host = "https://" + it["player"]["host"]
            purl = f"{self.instance}/release/{it['code']}.html"
            videos = list()

            for vid in it["player"]["playlist"].values():
                ititle = "Episode " + str(vid["serie"])
                video = Video(
                    title=ititle,
                    #playlist_title=title,
                    url=host+vid["hls"]["hd"],
                    #length=it["type"]["length"]
                )
                video.length=it["type"]["length"]
                video.isWatched = video.in_history(self.history)

                videos.append(video.to_json())

            playlist = Playlist(title, videos, url=purl)

            items.append(playlist.to_json())

        return items

    def get_items(self, params):
        if not 'query' in params: return list()
        return self.get_search(params)

    def save_config(self):
        self.config.set_option(self.category, 'api-instance', 'https://api.anilibria.tv/v2')
        self.config.set_option(self.category, 'instance', 'https://anilibria.tv')



